#include "../main.h"

typedef struct Node
{
    int number;
    struct Node* next;
}Node;

// 定义条件变量, 控制消费者线程
pthread_cond_t cond;
pthread_mutex_t mutex;
Node* head = NULL;

// 生产者的回调函数 
void* producer(void* arg);

// 消费者的回调函数
void* consumer(void* arg);

#define PRODUCER_NUMBER 5
#define CONSUMER_NUMBER 5

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    
    pthread_t producer_id[PRODUCER_NUMBER];
    pthread_t consumer_id[CONSUMER_NUMBER];

    for(int i = 0 ;i < PRODUCER_NUMBER;i++){
        pthread_create(producer_id+i,NULL,producer,NULL);
    }

    for(int i = 0 ;i < CONSUMER_NUMBER;i++){
        pthread_create(consumer_id+i,NULL,consumer,NULL);
    }

    for(int i = 0 ;i < PRODUCER_NUMBER;i++){
        pthread_join(producer_id[i],NULL);
    }
    
    for(int i = 0 ;i < CONSUMER_NUMBER;i++){
        pthread_join(consumer_id[i],NULL);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

// 消费者的回调函数
void* consumer(void* arg)
{
    while(1){
        pthread_mutex_lock(&mutex);

        while(NULL==head){
            pthread_cond_wait(&cond,&mutex);
        }
        Node* node =head;
        printf("消费者 number = %d tid = %ld \n",node->number,pthread_self());
        head=head->next;
        free(node);

        pthread_mutex_unlock(&mutex);

        sleep(rand()%3);
    }
    return NULL;
}

// 生产者的回调函数 
void* producer(void* arg)
{
    while(1){
        pthread_mutex_lock(&mutex);

        Node* node = (Node*)calloc(1,sizeof(Node));
        node->next=head;
        node->number=rand()%1000;
        head=node;
        printf("生产者 number = %d tid= %ld \n",head->number,pthread_self());

        pthread_mutex_unlock(&mutex);

        pthread_cond_broadcast(&cond);

        sleep(rand()%3);
    }
    return NULL;
}

